package controller

import (
	"errors"
	"fmt"
	"github.com/e421083458/golang_common/lib"
	"github.com/gin-gonic/gin"
	"tino_manager/dao"
	"tino_manager/dto"
	"tino_manager/middleware"
	"tino_manager/public"
)

type ManagerController struct {
}

func ManagerRegister(group *gin.RouterGroup) {
	manager := &ManagerController{}
	//管理员登录
	group.POST("/login", manager.Login)
	//添加管理员
	group.POST("/add", middleware.WeAppMiddleware(), manager.Add)
	//获取管理员列表
	group.GET("/page", middleware.WeAppMiddleware(), manager.Page)
	//获取用户信息
	group.GET("/detail", middleware.WeAppMiddleware(), manager.Detail)
	//修改管理员密码
	group.POST("/change_password", middleware.WeAppMiddleware(), manager.UpdatePassword)
	//修改管理员状态
	group.POST("/update_status", middleware.WeAppMiddleware(), manager.UpdateStatus)
	//删除管理员
	group.POST("/remove", middleware.WeAppMiddleware(), manager.Remove)
	//修改管理员
	group.POST("/update", middleware.WeAppMiddleware(), manager.Update)
	//开通或关闭消息提醒
	group.POST("/switch_message_status", middleware.WeAppMiddleware(), manager.SwitchMessage)
	//获取消息提醒状态
	group.GET("/message_status", middleware.WeAppMiddleware(), manager.GetMessageStatus)
}

func (m *ManagerController) Login(c *gin.Context) {
	params := &dto.ManagerLoginInput{}
	if err := params.BindValidParam(c); err != nil {
		middleware.ResponseError(c, 500, err, true)
		return
	}
	tx, err := lib.GetGormPool("default")
	if err != nil {
		middleware.ResponseError(c, 500, errors.New("登录失败"), true)
		return
	}
	manager := &dao.Manager{}
	if result := tx.Where(map[string]interface{}{
		"phone":     params.Phone,
		"is_delete": 0,
		"status":    0,
	}).First(manager); result.RowsAffected == 0 {
		middleware.ResponseError(c, 500, errors.New("登录失败"), true)
		return
	}
	//验证密码
	saltPassword := public.GenSaltPassword(manager.Salt, params.Password)
	if saltPassword != manager.Password {
		middleware.ResponseError(c, 500, errors.New("账号或密码错误"), true)
		return
	}
	if manager.OpenId == "" {
		//没有绑定openId
		appId := lib.GetStringConf("base.weapp.appId")
		appSecret := lib.GetStringConf("base.weapp.appSecret")
		err, resp := public.LoadUserOpen(appId, appSecret, params.Code)
		if err != nil {
			middleware.ResponseError(c, 500, errors.New("登录失败"), true)
			return
		}
		manager.OpenId = resp.OpenId
		if result := tx.Model(&dao.Manager{}).Where(map[string]interface{}{
			"id": manager.Id,
		}).Updates(manager); result.RowsAffected == 0 {
			middleware.ResponseError(c, 500, errors.New("登录失败"), true)
			return
		}
	}
	log := dao.Log{
		CreatedBy: fmt.Sprintf("%d", manager.Id),
		Key:       "manager_login",
	}
	log.Save(c, tx)
	middleware.ResponseSuccess(c, fmt.Sprintf("%d", manager.Id), true)
}
func (m *ManagerController) Add(c *gin.Context) {
	params := &dto.ManagerAddInput{}
	if err := params.BindValidParam(c); err != nil {
		middleware.ResponseError(c, 500, err, true)
		return
	}
	value, ok := c.Get("user_openId")
	if !ok {
		middleware.ResponseError(c, 500, errors.New("添加失败"), true)
		return
	}
	tx, err := lib.GetGormPool("default")
	if err != nil {
		middleware.ResponseError(c, 500, errors.New("添加管理员失败"), true)
		return
	}
	salt := public.CreateUUid()
	if salt == "" {
		middleware.ResponseError(c, 500, errors.New("添加管理员失败"), true)
		return
	}
	password := lib.GetStringConf("base.default.password")
	if params.Password != "" {
		password = params.Password
	}
	//查询是否已经有了用户
	manager := &dao.Manager{}
	if result := tx.Where(map[string]interface{}{
		"phone": params.Phone,
	}).First(manager); result.RowsAffected != 0 {
		middleware.ResponseError(c, 500, errors.New("此账号已注册"), true)
		return
	}
	manager = &dao.Manager{
		UserName:  params.UserName,
		Phone:     params.Phone,
		HeadImage: params.HeadImage,
		Password:  public.GenSaltPassword(salt, password),
		Salt:      salt,
		CreateBy:  fmt.Sprintf("%v", value),
	}
	if err := manager.Save(c, tx); err != nil {
		middleware.ResponseError(c, 500, errors.New("账号添加失败"), true)
		return
	}
	middleware.ResponseSuccess(c, "管理员添加成功", true)
}

func (m *ManagerController) Page(c *gin.Context) {
	params := &dto.ManagerPageInput{}
	if err := params.BindValidParam(c); err != nil {
		middleware.ResponseError(c, 500, err, true)
		return
	}
	tx, err := lib.GetGormPool("default")
	if err != nil {
		middleware.ResponseError(c, 500, errors.New("获取数据失败，请稍后重试"), true)
		return
	}
	total := int64(0)
	offset := (params.PageNumber - 1) * params.PageSize
	var list []dao.Manager
	query := tx.WithContext(c).Model(&dao.Manager{}).Where("is_delete=0").Order("create_at desc")
	if params.Type == "1" {
		query = query.Where("status = 0")
	}
	if params.Type == "2" {
		query = query.Where("status = 1")
	}
	if params.KeyWord != "" {
		query = query.Where("user_name LIKE ? OR phone LIKE ?", "%"+params.KeyWord+"%", "%"+params.KeyWord+"%")
	}
	query.Count(&total)
	if err := query.Limit(params.PageSize).Offset(offset).Find(&list).Error; err != nil {
		middleware.ResponseError(c, 500, errors.New("获取数据失败，请稍后重试"), true)
		return
	}
	out := &dto.ManagerPageOutput{
		Total: total,
	}
	for _, item := range list {
		out.List = append(out.List, dto.ManagerInfo{
			Id:            fmt.Sprintf("%d", item.Id),
			UserName:      item.UserName,
			Phone:         item.Phone,
			OpenId:        item.OpenId,
			MessageAppId:  item.MessageAppId,
			MessageOpenId: item.MessageOpenId,
			Status:        item.Status,
			HeadImage:     item.HeadImage,
			IsDelete:      item.IsDelete,
			CreatedAt:     item.CreatedAt.Format("2006-01-02 15:04:05"),
			UpdatedAt:     item.UpdatedAt.Format("2006-01-02 15:04:05"),
		})
	}
	middleware.ResponseSuccess(c, out, true)
}
func (m *ManagerController) Detail(c *gin.Context) {
	value, ok := c.Get("user_openId")
	if !ok {
		middleware.ResponseError(c, 500, errors.New("获取用户信息失败"), true)
		return
	}
	params := &dto.UserDetailInput{}
	if err := params.BindValidParam(c); err != nil {
		middleware.ResponseError(c, 500, err, true)
		return
	}
	tx, err := lib.GetGormPool("default")
	if err != nil {
		middleware.ResponseError(c, 500, errors.New("获取数据失败，请稍后重试"), true)
		return
	}
	queryMap := map[string]interface{}{}
	if params.Id != "" {
		queryMap["id"] = params.Id
	} else {
		queryMap["id"] = value
	}
	manager := &dao.Manager{}
	if result := tx.Where(queryMap).First(manager); result.RowsAffected == 0 {
		middleware.ResponseError(c, 500, errors.New("没有查到相关用户信息"), true)
		return
	}
	middleware.ResponseSuccess(c, manager, true)
}
func (m *ManagerController) UpdatePassword(c *gin.Context) {
	params := &dto.UpdatePasswordInput{}
	if err := params.BindValidParam(c); err != nil {
		middleware.ResponseError(c, 500, err, true)
		return
	}
	value, ok := c.Get("user_openId")
	if !ok {
		middleware.ResponseError(c, 500, errors.New("操作失败"), true)
		return
	}
	tx, err := lib.GetGormPool("default")
	if err != nil {
		middleware.ResponseError(c, 500, errors.New("操作失败"), true)
		return
	}
	manager := &dao.Manager{}
	if result := tx.Where(map[string]interface{}{
		"id":        value,
		"is_delete": 0,
		"status":    0,
	}).First(manager); result.RowsAffected == 0 {
		middleware.ResponseError(c, 500, errors.New("操作失败"), true)
		return
	}
	//验证密码
	saltPassword := public.GenSaltPassword(manager.Salt, params.OldPassword)
	if saltPassword != manager.Password {
		middleware.ResponseError(c, 500, errors.New("原始密码错误，请核对"), true)
		return
	}
	newPassword := public.GenSaltPassword(manager.Salt, params.Password)
	if result := tx.Model(&dao.Manager{}).Where("id = ?", value).Update("password", newPassword); result.Error != nil {
		middleware.ResponseError(c, 500, errors.New("操作失败"), true)
		return
	}
	middleware.ResponseSuccess(c, "修改成功", true)
}

func (m *ManagerController) UpdateStatus(c *gin.Context) {
	params := &dto.UserUpdateStatusInput{}
	if err := params.BindValidParam(c); err != nil {
		middleware.ResponseError(c, 500, err, true)
		return
	}
	tx, err := lib.GetGormPool("default")
	if err != nil {
		middleware.ResponseError(c, 500, errors.New("操作失败"), true)
		return
	}
	user := &dao.Manager{
		Status: params.Status,
	}
	if result := tx.Model(&dao.Manager{}).Where("id = ?", params.Id).Select("status").Updates(user); result.Error != nil {
		middleware.ResponseError(c, 500, errors.New("操作失败"), true)
		return
	}
	fmt.Println(params.Status)
	middleware.ResponseSuccess(c, "操作成功", true)
}
func (m *ManagerController) Remove(c *gin.Context) {
	params := &dto.ManagerRemoveInput{}
	if err := params.BindValidParam(c); err != nil {
		middleware.ResponseError(c, 500, err, true)
		return
	}
	tx, err := lib.GetGormPool("default")
	if err != nil {
		middleware.ResponseError(c, 500, errors.New("操作失败"), true)
		return
	}
	if result := tx.Model(&dao.Manager{}).Where("id = ?", params.Id).Update("is_delete", 1); result.Error != nil {
		middleware.ResponseError(c, 500, errors.New("操作失败"), true)
		return
	}
	middleware.ResponseSuccess(c, "操作成功", true)
}

func (m *ManagerController) Update(c *gin.Context) {
	params := &dto.ManagerUpdateInput{}
	if err := params.BindValidParam(c); err != nil {
		middleware.ResponseError(c, 500, err, true)
		return
	}
	tx, err := lib.GetGormPool("default")
	if err != nil {
		middleware.ResponseError(c, 500, errors.New("操作失败"), true)
		return
	}
	manager := &dao.Manager{
		HeadImage: params.HeadImage,
		UserName:  params.UserName,
		Phone:     params.Phone,
	}
	if result := tx.Model(&dao.Manager{}).Where("id = ?", params.Id).Select("head_image", "user_name", "phone").Updates(manager); result.Error != nil {
		middleware.ResponseError(c, 500, errors.New("操作失败"), true)
		return
	}
	middleware.ResponseSuccess(c, "操作成功", true)
}
func (m *ManagerController) SwitchMessage(c *gin.Context) {
	value, ok := c.Get("user_openId")
	if !ok {
		middleware.ResponseError(c, 500, errors.New("操作失败"), true)
		return
	}
	params := &dto.SwitchMessageInput{}
	if err := params.BindValidParam(c); err != nil {
		middleware.ResponseError(c, 500, errors.New("操作失败"), true)
		return
	}
	tx, err := lib.GetGormPool("default")
	if err != nil {
		middleware.ResponseError(c, 500, errors.New("操作失败"), true)
		return
	}
	if result := tx.Model(&dao.Manager{}).Where("id = ?", value).Update("open_message_status", params.OpenMessageStatus); result.Error != nil {
		middleware.ResponseError(c, 500, errors.New("操作失败"), true)
		return
	}
	middleware.ResponseSuccess(c, "操作成功", true)
}
func (m *ManagerController) GetMessageStatus(c *gin.Context) {
	value, ok := c.Get("user_openId")
	if !ok {
		middleware.ResponseError(c, 500, errors.New("获取用户信息失败"), true)
		return
	}
	params := &dto.GetMessageStatusInput{}
	if err := params.BindValidParam(c); err != nil {
		middleware.ResponseError(c, 500, errors.New("获取用户信息失败"), true)
		return
	}
	appId := lib.GetStringConf("base.message.appId")
	appSecret := lib.GetStringConf("base.message.appSecret")
	err, resp := public.LoadMessageOpen(appId, appSecret, params.Code)
	if err != nil {
		fmt.Println(err)
		middleware.ResponseError(c, 500, errors.New("获取用户信息失败"), true)
		return
	}
	tx, err := lib.GetGormPool("default")
	if err != nil {
		middleware.ResponseError(c, 500, errors.New("获取数据失败，请稍后重试"), true)
		return
	}
	user := &dao.Manager{}
	if result := tx.Where("id = ?", value).First(user); result.RowsAffected == 0 {
		middleware.ResponseError(c, 500, errors.New("没有查到相关用户信息"), true)
		return
	}
	if result := tx.Model(user).Where("id = ?", value).Update("message_open_id", resp.OpenId); result.RowsAffected == 0 {
		middleware.ResponseError(c, 500, errors.New("没有查到相关用户信息"), true)
		return
	}
	middleware.ResponseSuccess(c, user, true)
}
